<template>
    <div class="table">
            <div class="crumbs">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item><i class="icon iconfont icon-jifen"></i>项目管理-编辑项目</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="container">
                <div style="max-width:1000px;padding:10px 0 30px 0px">
                    <el-alert
                        title="建议上传的图片压缩之后再上传，便于小程序请求图片资源加载速度快"
                        type="warning"
                        show-icon>
                    </el-alert>
                </div>
                <el-form ref="form" label-width="160px">
                     <el-form-item label="项目分类：">
                        <el-cascader
                            :options="options"
                            expand-trigger="hover"
                            v-model="selectedOptions"
                            @change="handleChange">
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="项目类型：">
                        <el-select v-model="projectType" @change="changeType" placeholder="请选择项目类型" style="width:400px;" disabled="disabled">
                            <el-option label="普通项目" value="0"></el-option>
                            <el-option label="拼团项目" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="项目封面图：">
                        <div class="sola-upload clearfix">
                            <div class="sola-left clearfix" v-show="bannerPicture.length>0">
                                <div v-for="(item, index) in bannerPicture" class="sola-flex" :key="index">
                                    <img  :src="item" />
                                    <span class="delete" @click="delPicture(index,item,1)"><i class="el-alert__icon el-icon-error"></i></span>
                                </div>
                            </div>
                            <div class="sola-file-box">
                                <el-button type="primary" plain>上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
                                <input class="btn-file" type="file" @change="uploadBanner"/>
                                <span style="color:red;padding-left:10px;">（最多上传五张）建议上传的轮播图比例是3：2 示例750*490,每张图片控制在1MB以下</span>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="项目标题：">
                        <el-input v-model="title" placeholder="请输入项目标题" style="width:600px"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="原价：">
                        <el-input v-model="price" placeholder="请输入原价" style="width:600px"></el-input>
                    </el-form-item> -->
                    <el-form-item label="项目优惠价：" >
                        <el-input v-model="price" placeholder="请输入项目优惠价" type="number" style="width:600px"></el-input>
                    </el-form-item>
                    <el-form-item label="项目原价：">
                        <el-input type="number" v-model="collagePrice" placeholder="请输入项目原价" style="width:600px"></el-input>
                    </el-form-item>
                    <el-form-item label="是否可以预约：">
                        <el-radio v-model="isMake" label="0" border >可预约</el-radio>
                        <el-radio v-model="isMake" label="1" border>不可预约</el-radio>
                    </el-form-item>
                    <el-form-item label="项目详情图：">
                        <div class="sola-upload clearfix">
                            <div class="sola-left clearfix" v-show="detailPicture.length>0">
                                <div v-for="(item, index) in detailPicture" class="sola-flex" :key="index">
                                    <img  :src="item" />
                                    <span class="delete" @click="delPicture(index,item,2)"><i class="el-alert__icon el-icon-error"></i></span>
                                </div>
                                
                            </div>
                            <div class="sola-file-box">
                                <el-button type="primary" plain>上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
                                <input class="btn-file" type="file" accept="image/*" @change="uploadDetail"/>
                                <span style="color:red;padding-left:10px;">建议上传的详情图宽度750高度自适应,图片建议分割几张图片上传,每张图片控制在1MB以下</span>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="项目说明：">
                        <div class="sola-upload clearfix">
                            <div class="sola-left clearfix" v-show="explainPicture.length>0">
                                <div v-for="(item, index) in explainPicture" class="sola-flex" :key="index">
                                    <img  :src="item" />
                                    <span class="delete" @click="delPicture(index,item,3)"><i class="el-alert__icon el-icon-error"></i></span>
                                </div>
                                
                            </div>
                            <div class="sola-file-box">
                                <el-button type="primary" plain>上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
                                <input class="btn-file" type="file" accept="image/*" @change="uploadExplain"/>
                                <span style="color:red;padding-left:10px;">建议上传的详情图宽度750高度自适应,图片建议分割几张图片上传,每张图片控制在1MB以下</span>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="拼团规则：" v-show="isShowCollageRule">
                        <div class="sola-upload clearfix">
                            <div class="sola-left clearfix" v-show="collagePicture.length>0">
                                <div v-for="(item, index) in collagePicture" class="sola-flex" :key="index">
                                    <img  :src="item" />
                                    <span class="delete" @click="delPicture(index,item,4)"><i class="el-alert__icon el-icon-error"></i></span>
                                </div>
                                
                            </div>
                            <div class="sola-file-box">
                                <el-button type="primary" plain>上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
                                <input class="btn-file" type="file" accept="image/*" @change="uploadCollage"/>
                                <span style="color:red;padding-left:10px;">建议上传的详情图宽度750高度自适应,图片建议分割几张图片上传,每张图片控制在1MB以下</span>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="是否是热门项目：">
                        <el-radio v-model="isHot" label="0" border >否</el-radio>
                        <el-radio v-model="isHot" label="1" border>是</el-radio>
                        <span style="color:red;font-size:12px;">* 如果设置了热门项目，数据除了展示门店中，还会展示在首页热门项目更多列表中</span>
                    </el-form-item>
                    <div style="height:30px;"></div>
                    <el-form-item >
                        <el-button type="primary" size="medium " @click="onSubmit">保存</el-button>
                    </el-form-item>
                </el-form>
                
            </div>

            <!-- 删除提示框 -->
            <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
                <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="delVisible = false">取 消</el-button>
                    <el-button type="primary" @click="deleteRow">确 定</el-button>
                </span>
            </el-dialog>
        </div>
</template>
<script>
export default {
    name:"detail",
    data (){
        return{
            form:{

            },
            id:'',//项目id
            accept: 'image/gif, image/jpeg, image/png, image/jpg', //图片上传类型
            options:[],//级联绑定的数据
            selectedOptions:[],//级联选中的数据
            bannerPicture:[],//存放的项目轮播图
            projectType:"", //项目类型 
            title:'',//项目标题
            price:"",//原价
            collagePrice:"",//拼团价格
            detailPicture:[],//存放的项目详情图
            explainPicture:[],//存放的项目说明图
            collagePicture:[], //拼团规则图
            isMake:"0", //是否可以预约
            isHot:"0", //是否是热门项目：0否，1是
            idx:'',//要删除的图片ID
            typeId:'',//要删除的类型
            delVisible:false, //删除提示框默认隐藏
            isShowCollageRule:false,//是否显示拼团规则
        }
    },
    created (){
        this.id = this.$route.params.id;//获得id
        //console.log(this.id);
        //可以根据参数来区分是 编辑还是新增状态
        // console.log(this.$global.app.API_URL)
        //获取项目的分类数据
        this.getClassify();
        //获取项目详情数据
        this.getProjectData();
    },
    methods:{
        //获得项目详情
        getProjectData(){
            const querystring = require('querystring');
            const param ={
                id: this.id,
                type : 0,
                pageIndex: 1,
                pageSize: 10
            }
            
            this.$axios.post('/manage/item/list',querystring.stringify(param))
                .then(response=>{
                    // console.log(response);
                    if(response.data.code==200){
                        let data = response.data.data.currData[0]
                        
                        //判断项目类型
                        if(data.is_collage == 1){
                            this.projectType = "1";
                            this.isShowCollageRule = true;
                        }else{
                            this.projectType = "0";
                            this.isShowCollageRule = false;
                        }
                        //判断是否可预约
                        if(data.is_reservation == 0){
                           this.isMake = "0"; 
                        }else{
                            this.isMake = "1"; 
                        }
        
                        this.title = data.name;
                        this.price = data.price;
                        this.collagePrice = data.original_price;//赋值项目原价
                        // this.memberPrice = data.collage_price;
                        //this.categoryLevel1 = data.category_level1;
                        //this.categoryLevel2 = data.category_level2;
                        this.selectedOptions = [data.category_level1,data.category_level2];//分类默认选中
                        this.bannerPicture = JSON.parse(data.banner_img);//项目封面图
                        this.detailPicture = JSON.parse(data.detail);//项目详情图
                        this.explainPicture = JSON.parse(data.item_explain);//项目说明图
                        if(data.is_collage==1){
                            this.collagePicture = JSON.parse(data.item_rule);//拼团规则图
                        }
                        this.isHot =""+data.is_hot+"";
                        //console.log(this.detailImgs); 
                    }else{
                        console.log(response.data.msg)  
                    }
                })
                .catch(error=>{
                    console.log(error); 
                });
        },
        //获得分类数据
        getClassify(){
            var _this = this;
            this.$axios.get('/manage/item/categoryList', {
                params: {
                    pageIndex:1,
                    pageSize:999
                }
            })
            .then(function (response) {
                // console.log(response);
                if(response.data.code==200){
                    var data = response.data.data;
                    var array = [];
                    data.forEach(element => {
                        //console.log(element);
                        let obj ={};
                        obj.value = element.id;
                        obj.label = element.alias;
                        obj.alias = element.alias;
                        var cities = [];
                        element.children.forEach(rows=>{
                            let subObj ={};
                            subObj.value = rows.id;
                            subObj.label = rows.name;
                            cities.push(subObj);
                        });
                        obj.children =cities;
                        array.push(obj);
                    });
                    //console.log(array);
                    _this.options = array;
                }else{
                    console.log("获取分类失败");
                }
            })
            .catch(function (error) {
                console.log(error);
            });
        },
        //级联选择器 记录选中的分类 
        handleChange(event){
           
        },
        //触发项目类型
        changeType(event){
            
            if(event==1){
                //拼团项目
                
                this.isShowCollageRule = true;  
            }else{
                //普通项目
                
                this.isShowCollageRule = false;   
            }
        },
        // file 文件源转换base64 并且按照最低像素压缩
        getBase64(file,callback){
            //图片文件转base64
            var maxWidth = 640;  
            if(file.files && file.files[0]){  
                var thisFile = file.files[0];  
                var reader = new FileReader();  
                reader.readAsDataURL(file.files[0]);  
                reader.onload = function(event){  
                    var imgUrl = event.target.result;  
                    /*var img = new Image();  
                    img.onload = function(){  
                        var canvasId = 'canvasBase64Imgid',  
                        canvas = document.getElementById(canvasId);  
                        if(canvas!=null){document.body.removeChild(canvas);}  
                        var canvas = document.createElement("canvas");  
                        canvas.innerHTML = 'New Canvas';  
                        canvas.setAttribute("id", canvasId);  
                        canvas.style.display='none';  
                        document.body.appendChild(canvas);  
                        canvas.width = this.width;  
                        canvas.height = this.height;  
                        var imageWidth = this.width,   
                        imageHeight = this.height;  
                        if (this.width > maxWidth){  
                            imageWidth = maxWidth;  
                            imageHeight = this.height * maxWidth/this.width;  
                            canvas.width = imageWidth;  
                            canvas.height = imageHeight;  
                        }  
                        var context = canvas.getContext('2d');  
                        context.clearRect(0, 0, imageWidth, imageHeight);  
                        context.drawImage(this, 0, 0, imageWidth, imageHeight);  
                        var base64 = canvas.toDataURL('image/png',1);  
                        canvas.remove();
                       
                    }  
                    img.src = imgUrl;  */
                     callback(imgUrl);
                }  
                //reader.readAsDataURL(file.files[0]);  
                
            }  
        },
        deleteRow(){
            if(this.typeId==1){
                //项目封面图
                this.bannerPicture.splice(this.idx,1);
            }else if(this.typeId==2){
                //项目详情图
                this.detailPicture.splice(this.idx,1);
            }else if(this.typeId==3){
                //详情说明图
                this.explainPicture.splice(this.idx,1);
            }else if(this.typeId==4){
                //项目拼团规则
                this.collagePicture.splice(this.idx,1);
            }
            this.$message.success('删除成功');
            this.delVisible = false;
        },
        //删除图片
        delPicture(index, row,typeId){
            //当前记录的下标
            this.idx = index;
            this.typeId = typeId;
            this.delVisible = true;
        },
        //触发项目封面图 file
        uploadBanner(event){
            var _event = event;
            var _this = this;
            let reader =new FileReader();  
            let img1=event.target.files[0];  
            let type=img1.type;//文件的类型，判断是否是图片  
            let size=img1.size;//文件的大小，判断图片的大小
            const files = event.target;  
            if(this.accept.indexOf(type) == -1){  
                this.$message({
                    message: '请选择gif,jpeg,png,jpg格式图片上传',
                    type: 'warning'
                });
                return false;  
            }  
            else if(size>1048576){  
                this.$message({
                    message: '请选择1M以内的图片上传',
                    type: 'warning'
                }); 
                return false;  
            }else if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            }else {
                //把图片转换成功base64
                _this.getBase64(files,(url)=>{
                    var base = url ;
                    const querystring = require('querystring');
                    const param ={
                        base64:base
                    }
                    this.$axios.post('/api/common/upload/base64',querystring.stringify(param)).then(response=>{
                        console.log(response);
                        if(response.data.code==200){
                            this.$message({
                                message: '恭喜你，图片上传成功',
                                type: 'success'
                            });
                            this.bannerPicture.push(response.data.data);
                            
                        }else{
                            this.$notify.error({
                                title: '上传图片失败',
                                duration:2000,
                                message: '失败原因：'+response.data.msg
                            });
                        }

                    }).catch(error=>{
                        console.log(error);
                    });
                    
                });
                
            }
        },
        //触发项目详情图 file 
        uploadDetail(event){
            var _event = event;
            var _this = this;
            let reader =new FileReader();  
            let img1=event.target.files[0];  
            let type=img1.type;//文件的类型，判断是否是图片  
            let size=img1.size;//文件的大小，判断图片的大小
            const files = event.target;  
            if(this.accept.indexOf(type) == -1){  
                this.$message({
                    message: '请选择gif,jpeg,png,jpg格式图片上传',
                    type: 'warning'
                });
                return false;  
            }  
            else if(size>1048576){  
                this.$message({
                    message: '请选择1M以内的图片上传',
                    type: 'warning'
                }); 
                return false;  
            }else if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            }else {
                //把图片转换成功base64
                _this.getBase64(files,(url)=>{
                    var base = url ;
                    const querystring = require('querystring');
                    const param ={
                        base64:base
                    }
                    this.$axios.post('/api/common/upload/base64',querystring.stringify(param)).then(response=>{
                        console.log(response);
                        if(response.data.code==200){
                            this.$message({
                                message: '恭喜你，图片上传成功',
                                type: 'success'
                            });
                            this.detailPicture.push(response.data.data);
                            
                        }else{
                            this.$notify.error({
                                title: '上传图片失败',
                                duration:2000,
                                message: '失败原因：'+response.data.msg
                            });
                        }

                    }).catch(error=>{
                        console.log(error);
                    });
                    
                });
            }
        },
        //触发项目说明 file
        uploadExplain(event){
            var _event = event;
            var _this = this;
            let reader =new FileReader();  
            let img1=event.target.files[0];  
            let type=img1.type;//文件的类型，判断是否是图片  
            let size=img1.size;//文件的大小，判断图片的大小
            const files = event.target;  
            if(this.accept.indexOf(type) == -1){  
                this.$message({
                    message: '请选择gif,jpeg,png,jpg格式图片上传',
                    type: 'warning'
                });
                return false;  
            }  
            else if(size>1048576){  
                this.$message({
                    message: '请选择1M以内的图片上传',
                    type: 'warning'
                }); 
                return false;  
            }else if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            }else {
                //把图片转换成功base64
                _this.getBase64(files,(url)=>{
                    var base = url ;
                    const querystring = require('querystring');
                    const param ={
                        base64:base
                    }
                    this.$axios.post('/api/common/upload/base64',querystring.stringify(param)).then(response=>{
                        console.log(response);
                        if(response.data.code==200){
                            this.$message({
                                message: '恭喜你，图片上传成功',
                                type: 'success'
                            });
                            this.explainPicture.push(response.data.data);
                            
                        }else{
                            this.$notify.error({
                                title: '上传图片失败',
                                duration:2000,
                                message: '失败原因：'+response.data.msg
                            });
                        }

                    }).catch(error=>{
                        console.log(error);
                    });
                    
                });
            }
        },
        //触发拼团规则图 file
        uploadCollage(event){
            var _event = event;
            var _this = this;
            let reader =new FileReader();  
            let img1=event.target.files[0];  
            let type=img1.type;//文件的类型，判断是否是图片  
            let size=img1.size;//文件的大小，判断图片的大小
            const files = event.target;  
            if(this.accept.indexOf(type) == -1){  
                this.$message({
                    message: '请选择gif,jpeg,png,jpg格式图片上传',
                    type: 'warning'
                });
                return false;  
            }  
            else if(size>1048576){  
                this.$message({
                    message: '请选择1M以内的图片上传',
                    type: 'warning'
                }); 
                return false;  
            }else if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            }else {
                //把图片转换成功base64
                _this.getBase64(files,(url)=>{
                    var base = url ;
                    const querystring = require('querystring');
                    const param ={
                        base64:base
                    }
                    this.$axios.post('/api/common/upload/base64',querystring.stringify(param)).then(response=>{
                        console.log(response);
                        if(response.data.code==200){
                            this.$message({
                                message: '恭喜你，图片上传成功',
                                type: 'success'
                            });
                            this.collagePicture.push(response.data.data);
                            
                        }else{
                            this.$notify.error({
                                title: '上传图片失败',
                                duration:2000,
                                message: '失败原因：'+response.data.msg
                            });
                        }

                    }).catch(error=>{
                        console.log(error);
                    });
                    
                });
            }
        },
        //确认修改
        onSubmit (){

           if(this.selectedOptions.length<1){
                this.$notify.info({title: '提示',message: '请先选择项目分类'});
                return false;
            }else if(this.projectType==""){
                this.$notify.info({title: '提示',message: '请先选择项目类型'});
                return false;
            }else if(this.bannerPicture.length<1){
                this.$notify.info({title: '提示',message: '项目封面图至少要上传一张'});
                return false;
            }else if(this.title==""){
                this.$notify.info({title: '提示',message: '请填写项目标题'});
                return false;
            }else if(this.price==""){
                this.$notify.info({title: '提示',message: '请填写项目优惠价'});
                return false;
            }
            else if(this.collagePrice==""){
                this.$notify.info({title: '提示',message: '请填写项目原价'});
                return false;
            }
            else if(this.detailPicture.length<1){
                this.$notify.info({title: '提示',message: '请上传项目详情图，至少上传一张'});
                return false;
            }
            else if(this.explainPicture.length<1){
                this.$notify.info({title: '提示',message: '请上传项目说明图，至少上传一张'});
                return false;
            }else if(this.collagePicture.length<1 && this.projectType==1){
                //如果是拼团提示上传拼团规则图
                this.$notify.info({title: '提示',message: '请上传拼团规则图，至少上传一张'});
                return false;
            }else{
                let param ={}
                //拼团项目
                param.id=this.id;//项目id
                param.categoryLevel1=this.selectedOptions[0];//项目分类1级
                param.categoryLevel2=this.selectedOptions[1];//项目分类2级
                param.name=this.title;//项目名称
                param.imgList=JSON.stringify(this.bannerPicture); // 项目封面图  图片列表数组JSON字符串
                param.price=parseFloat(this.price);//项目价格
                param.originalPrice =parseFloat(this.collagePrice); // 项目原价
                param.detail=JSON.stringify(this.detailPicture);//项目详情
                param.itemExplain=JSON.stringify(this.explainPicture);//项目说明
                param.isCollage=parseInt(this.projectType);//是否是拼团项目：0普通项目，1拼团项目
                param.isReservation=parseInt(this.isMake);//是否可预约：0可以，1不可以
                param.collagePrice=parseFloat(this.price);//拼团项目情况时：拼团价格
                param.collageLimit=3;//拼团人数要求
                param.collageTime=168;//拼团到期时间：小时  6小时 示例6
                param.itemRule=[]; //拼团项目时：拼团规则
                param.isHot = parseInt(this.isHot);  //是否是热门项目：0否，1是
                if(param.isCollage==1){
                    //拼团规则详情
                    param.itemRule=JSON.stringify(this.collagePicture) //拼团项目时：拼团规则
                }
                //console.log(param)
                this.onSubmitAjax(param);
            }
        },
        //提交到服务器中保存项目
        onSubmitAjax(param){
            let _this = this;
            const querystring = require('querystring');
            this.$axios.post('/manage/item/update',querystring.stringify(param)).then(response=>{
                //console.log(response);
                if(response.data.code==200){
                    this.$message({
                        message: '恭喜你，项目修改成功',
                        type: 'success'
                    });
                    //this.$router.push({ path:'/project' })
                    setTimeout(function(){
                        _this.$router.push({ path:'/project'})
                    },1500);

                }else{
                    this.$notify.error({
                        title: '项目发布失败',
                        duration:2000,
                        message: '失败原因：'+response.data.msg
                    });
                }

            }).catch(error=>{
                console.log(error);
            });
        }
    }
}
</script>
<style lang="stylus" scoped>
    .el-form-item .el-cascader{
        width :400px;
    }
    .el-cascader-menus .el-cascader-menu{
        width :240px
    }
    .sola-upload{
        .sola-left{
            width :100%;
            height :auto;
            .sola-flex{
                float:left
                width: 360px;
                height: 180px;
                margin-bottom 20px;
                margin-right:15px;
                position:relative;
                .delete{
                    position:absolute;
                    top:2px;
                    right:13px;
                    color: #f56c6c;
                    display:inline-block;
                    padding:5px 5px;
                    .el-alert__icon{font-size:28px;cursor:pointer}
                }
                img {
                    width:100%;
                    height:100%;
                }
            }
        }
        .sola-file-box{
            position:relative;
            .btn-file{
                position:absolute;
                top:0;
                left:0;
                z-index 1;
                opacity:0;
                width :120px;
                height :40px;
                outline: 0;
                background-color :none;
                cursor:pointer;
            }
        }

    }
</style>


